﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MShop.Core.Domain;
using System.Linq.Expressions;

namespace MShop.Core.Service
{
    public class RecursionSortService<T> : IRecursionSort<T> where T : INode<T>
    {

        //#region IRecursionSort<T> Members

        //public void Recursion(IEnumerable<T> objects, ref IList<T> list, ref int rowIndex, Expression<Func<T, bool>> expr = null)
        //{

        //    IEnumerable<T> enums = Enumerable.Empty<T>();
        //    if (expr != null)
        //    {
        //        enums = objects.Where(expr.Compile()).AsEnumerable();
        //    }
        //    else
        //    {
        //        enums = objects;
        //    }

        //    foreach (var item in enums.ToList())
        //    {
        //        item.NodeId = rowIndex;
        //        list.Add(item);
        //        rowIndex++;
        //        Expression<Func<T, bool>> myexp = (x) => x.Parent.Key == item.Key;
        //        Recursion(item.ChildNodes, ref list, ref rowIndex, myexp);

        //    }
        //}

        //#endregion

        


        public void Recursion(IEnumerable<T> objects, ref IList<T> list, ref int rowIndex, object key = null)
        {           
            var enums = objects.ToList().Where(x => x.ParentId == (int?)key);
            foreach (var item in enums)
            {
                item.NodeId = rowIndex;
                list.Add(item);
                rowIndex++;
                Recursion(item.ChildNodes, ref list, ref rowIndex, item.Key);

            }
        }

        
    }
}